<?php

namespace Gaolei\YiiRBAC\models\form;

use Gaolei\YiiRBAC\models\Adminer;
use yii\base\Model;

/**
 * Description of ChangePassword
 *
 * @author Misbahul D Munir <misbahuldmunir@gmail.com>
 * @since 1.0
 */
class ChangePwd extends Model
{
    public $old_pass;
    public $new_pass;
    public $con_pass;
    private $_user;

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['old_pass', 'new_pass'], 'required', 'message' => '{attribute}不能为空'],
            ['new_pass', 'string', 'min' => 6, 'tooShort' => '密码至少填写6位'],
            //比较朗次输入的密码
            ['con_pass', 'compare', 'compareAttribute' => 'new_pass', 'message' => '两次密码不一致'],
        ];
    }

    /**
     * 修改密码操作
     * @return bool
     * @throws \yii\base\Exception
     */
    public function updatePwd(): bool
    {
        if (!$this->validate()) {
            \Yii::$app->session->setFlash('error','数据验证失败');
            return false;
        }
        if ($model = $this->getUser()) {
            if($model->validatePassword($this->old_pass)){
                $model->setPassword($this->new_pass);
                $model->generateAuthKey();
                if($model->save(false)){
                    \Yii::$app->session->setFlash('success','密码更新成功');
                    return true;
                }
                \Yii::$app->session->setFlash('error','密码更新失败');
            }else{
                \Yii::$app->session->setFlash('error','原密码输入错误');
            }
        }else{
            \Yii::$app->session->setFlash('error','用户不存在');
        }
        return false;
    }

    /**
     * 获取user对象
     * @return Adminer|null
     */
    protected function getUser()
    {
        if ($this->_user === null) {
            $this->_user = Adminer::findOne(\Yii::$app->user->identity->id);
        }
        return $this->_user;
    }
}
